package image;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
/**Used to handle a connection to a single client. 
 * The client will receive a stream of data, but is not allowed to send data.
 * The Server automatically allows another client to connect if the connection to the first client is broken.*/
public class Server
	{
	private ServerSocket myService;
	Accepter accepter;
	Socket socket = null;
	OutputStream os;
	
	public Server()
		{
		try
			{myService = new ServerSocket(1337);}
		catch (IOException e)
			{e.printStackTrace();}
		
		accepter = new Accepter();
		accepter.setDaemon(true);
		accepter.start();
		}
	
	//Connection accepter thread
	private class Accepter extends Thread
		{
		public void run()
			{
			try
				{
				System.out.println("Waiting for connection");
				socket = myService.accept();
				os = socket.getOutputStream();
				System.out.println("Got connection!");
				}
			catch (SocketException e)
				{System.out.println("Server Socket destroyed");}
			catch (IOException e)
				{e.printStackTrace();}
			}
		}

	public boolean sendFloat(float f)
	{
	if(socket == null)
		return false;
	else
		{
		try
			{
			ByteBuffer buf = ByteBuffer.allocate(4);
			buf.putFloat(f);
			os.write(buf.array());
			return true;
			}
		catch (IOException e)
			{
			System.err.println("Client disconnected!");
			e.printStackTrace();
			socket = null;
			os = null;
			accepter = new Accepter();
			accepter.setDaemon(true);
			accepter.start();
			return false;
			}
		}
	}
	public boolean sendInt(int f)
	{
	if(socket == null)
		return false;
	else
		{
		try
			{
			ByteBuffer buf = ByteBuffer.allocate(4);
			buf.putInt(f);
			os.write(buf.array());
			return true;
			}
		catch (IOException e)
			{
			System.err.println("Client disconnected!");
			e.printStackTrace();
			socket = null;
			os = null;
			accepter = new Accepter();
			accepter.setDaemon(true);
			accepter.start();
			return false;
			}
		}
	}

	public boolean sendByte(int i)
		{
		if(socket == null)
			return false;
		else
			{
			try
				{
				os.write(i);
				return true;
				}
			catch (IOException e)
				{
				System.err.println("Client disconnected!");
				e.printStackTrace();
				socket = null;
				os = null;
				accepter = new Accepter();
				accepter.setDaemon(true);
				accepter.start();
				return false;
				}
			}
		}
	}
